/*
 *  buffer.c
 *  ProducerConsumer
 *
 * Operating Systems Concepts Essentials
 *	Skeleton Program for buffer	p.266
 *
 *  Created by digi on 10/24/12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 *	EECE 315
 *	Project #2
 *	
 *	Procucer-Consumer Problem
 *	
 *	Authors:
 *			Mohamed Ali
 *			Donald Cheng
 *			Krzysztof Mazurek
 *			Ishan Sahay
 *	
 *	Date: 24 / Oct / 2012
 *	
 */


#include <pthread.h> 
#include <semaphore.h>

#include "buffer.h"


//buffer_item buffer[BUFFER_SIZE];

/* the buffer */ 

//Outlined in 6.10 and 6.11
int insert_item(buffer_item item) { 
	/* insert item into buffer
	 return 0 if successful, otherwise 
	 return -1 indicating an error condition */
	
	int flag = -1;
	
	/* acquire the semaphore Empty */ 
	sem_wait(&empty);
	
	/*** critical section ***/
	
	/* acquire the mutex lock */
	pthread_mutex_lock(&mutex);
	
	/*** critical section ***/
		/*
		 buffer[(emptyIndex)% BUFFER_SIZE] = item;
		 emptyIndex++;
		 */
	
	buffer[ (fullIndex+1) % BUFFER_SIZE ] = item;
	emptyIndex = (emptyIndex+1) % BUFFER_SIZE;
	
	flag = 0;
	
	/* release the mutex lock */ 
	pthread_mutex_unlock(&mutex);
	
	/* release the semaphore Full */ 
	sem_post(&full);
	
	
	return flag;
}

int remove_item(buffer_item *item) { 
	/* remove an object from buffer
	 placing it in item 
	 return 0 if successful, otherwise 
	 return -1 indicating an error condition */
	
	int flag = -1;
	
	/* acquire the semaphore Full */ 
	sem_wait(&full);
	
	/*** critical section ***/

	/* acquire the mutex lock */ 
	pthread_mutex_lock(&mutex);
	
	/*** critical section ***/	
	*item = buffer[(emptyIndex+1)% BUFFER_SIZE];
	fullIndex = (fullIndex+1) % BUFFER_SIZE;
	
	flag = 0;
	
	/* release the mutex lock */ 
	pthread_mutex_unlock(&mutex);
	
	/* release the semaphore Empty */ 
	sem_post(&empty);
	

	
	return flag;
	
}
